class OrdersController < ManageController
 layout "background"
 before_filter:has_shop,
                :only=>[:shop_order_list,:shop_order_show]
 before_filter:has_order,
                :only=>[:shop_order_show,:user_order_show,:show,:shop_order_ps]

  def has_shop
    begin
      @shop=Shop.find_by_user_id(session[:user_id])
    rescue ActiveRecord::RecordNotFound
      redirect_to(:controller=>:manage_shop,:action=>:shop_new)
    end
  end
  
  def has_order
    begin
      user=User.find(session[:user_id])
      @order=Order.find(params[:id])     
    rescue ActiveRecord::RecordNotFound
      @order=nil
    else
      if @order.shop.user_id==user.id||@order.user_id==user.id
        @items=LineItem.find(:all,:conditions=>["order_id=?",@order.id])
      else
        @order=nil
        notice("你无权限查看该订单！")
      end
    end
  end
  
  def shop_order_list
    @orders=Order.paginate(:all,:conditions=>["shop_id=?",@shop.id],
                                      :page => params[:page]||1,:per_page => 10)
  end
  
  def shop_order_ps
    unless @order
      notice("你无权限查看该订单！")
      redirect_to(:action=>:shop_order_list)
    else
      if OrderManager.product_sent(@order)
        notice("成功发货！")
      else
        notice("发货失败！")
      end
      redirect_to(:action=>:show,:id=>@order.id)
    end
  end
  
  def user_pay
    @cart=find_cart
    user=User.find(session[:user_id])
    shop=Shop.find(@cart.shop_id)
    order=Order.get_paid_order(:user=>user,:shop=>shop,:cart=>@cart)
    if OrderManager.paid_to_third(order)
      flash[:notice]="save successful!"
    else
      flash[:notice]="save fail!"
    end
    empty_cart
    redirect_to(:controller=>"orders",:action=>"show",:id=>order.id)
  end
  
  def user_order_list
   # @orders=Order.find(:all,:conditions=>["orders.user_id=?",session[:user_id]])
   @orders=Order.paginate(:all,:conditions=>["orders.user_id=?",session[:user_id]],
                                      :page => params[:page]||1,:per_page => 10)
  end
  
  def new_order
    @cart=find_cart
  end
  
  def paid_to_seller
    order=Order.find(params[:id])
    if OrderManager.paid_to_seller(order)
      flash[:notice]="save successful!"
    else
      flash[:notice]="save fail!"
    end
    redirect_to(:action=>:show,:id=>order.id)
  end
  
  def show
    unless @order
      redirect_to(:controller=>:manage,:action=>:error_msg)
    end
  end
  
  private  
  def find_cart
    session[:cart] ||=Cart.new
  end
  
  def empty_cart
    session[:cart]=nil
  end
end
